{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](http://colab.research.google.com/github/asteroid-team/asteroid/blob/master/notebooks/04_ProcessLargeAudioFiles.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Process large audio files\n",
    "When running inference with a separation/enhancement model, long wav files can\n",
    "cause CPU freeze/GPU OOM. Asteroid provides the `LambdaOverlapAdd` module that\n",
    "decomposes the input signal in overlapping chunks, apply the desired lambda function\n",
    "and re-combines the segment using overlap-add.\n",
    "Pair it with a pretrained model to enhance your long files !"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "from asteroid import ConvTasNet\n",
    "from asteroid.dsp.overlap_add import LambdaOverlapAdd\n",
    "\n",
    "\n",
    "nnet = ConvTasNet(n_src=2)\n",
    "continuous_nnet = LambdaOverlapAdd(\n",
    "\t\tnnet=nnet,  # function to apply to each segment.\n",
    "\t\tn_src=2,  # number of sources in the output of nnet\n",
    "\t\twindow_size=64000,  # Size of segmenting window\n",
    "\t\thop_size=None,  # segmentation hop size\n",
    "\t\twindow=\"hanning\",  # Type of the window (see scipy.signal.get_window\n",
    "\t\treorder_chunks=True,  # Whether to reorder each consecutive segment.\n",
    "\t\tenable_grad=False,  # Set gradient calculation on of off (see torch.set_grad_enabled)\n",
    ")\n",
    "\n",
    "# Instantiate long wav (1min) that would OOM\n",
    "wav = torch.randn(1, 1, 500000)\n",
    "out_wavs = continuous_nnet.forward(wav)\n",
    "# Or on GPU\n",
    "continuous_nnet.cuda()\n",
    "wav = wav.cuda()\n",
    "out_wavs_gpu = continuous_nnet.forward(wav)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
